package site.zhouinfo.math;

/**
 * 二分查找开方
 *
 * @author zhou
 * @create 2016-12-30 14:38
 * @email zhouinfo@qq.com
 */
public class Sqrt {

    public static double BinarySearchBySqrt(double x, double p) {
        if (x < 0) {
            return -1;
        }
        if (x == 0) {
            return 0;
        }

        double max = x;    //最大值
        double min = 0.0;    //最小值
        double mid = x / 2;    //中间值
        int i = 0;
        while (!(x - p < mid * mid && mid * mid < x + p)) {
            mid = (max + min) / 2;
            if (mid * mid < x - p) {
                min = mid;
            }
            if (x + p < mid * mid) {
                max = mid;
            }
            i++;
        }
        System.out.println("迭代次数:\t\t\t" + i);
        return mid;
    }

    public static void main(String[] args) {
        double x = 3.1;
        double p = 0.0001;

        System.out.println("Math.sqrt():\t\t" + Math.sqrt(x));
        double mid = BinarySearchBySqrt(x, p);
        System.out.println("二分法开方值\t\t\t" + x + "\t\t\t误差:\t" + Double.toString(p));
        System.out.println("二分法取开方\t\t\t" + mid);
        System.out.println("二分法取开方的误差:\t" + Double.toString(x - mid * mid));
        System.out.println("二分法与Math差别:\t\t" + Double.toString(Math.sqrt(x) - mid));
    }
}
